"""
-- coding: utf-8 --
@Time : 2023/09/15
@Author : 张书译
@Describe:读取yaml文件
"""

import yaml
from ruamel import yaml as ya
import config


class ReadYaml:

    def __init__(self, path=config.config_yaml):
        # :param yaml_file: yaml文件地址
        self.yaml_file = path

    def read_yaml_data(self):
        """读取yaml文件数据
        :return:
        """
        yaml_file = self.yaml_file.replace('\\', '/')
        with open(yaml_file, 'r', encoding="utf-8") as fr:
            return yaml.load(fr, Loader=yaml.SafeLoader)

    def write_yaml_file(self, obj):
        """把对象obj写入yaml文件
        :param obj: 数据对象
        :return:
        """
        with open(self.yaml_file, 'w', encoding='utf-8') as fw:
            yaml.dump(obj, fw, Dumper=ya.RoundTripDumper, allow_unicode=True)

    def rewrite_yaml_file(self, mode, section, value):
        import yaml
        with open(self.yaml_file, encoding='utf-8') as fp:
            read_yml_str = fp.read()  # 读出来是字符串
            d = yaml.safe_load(read_yml_str)  # 用load方法转字典
        d[mode][section] = value
        with open(self.yaml_file, 'w', encoding='utf-8') as f:
            yaml.dump(d, f, allow_unicode=True)
